package com.krtech.wecard.module.mayi.task;

import com.krtech.wecard.config.WecardRedisTemplate;
import com.krtech.wecard.module.mayi.MayiPayEnums;
import com.krtech.wecard.module.mayi.entity.MayiPayList;
import com.krtech.wecard.module.mayi.service.MayiPayListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class MayiPinniedTask {

    @Autowired
    private WecardRedisTemplate redisTemplate;

    @Autowired
    private MayiPayListService mayiPayListService;

    @Scheduled(cron = "0/30 * * * * ? ")
    public void userTask(){
        //扫描redis以xxx开头的
//        redisTemplate.set("replace:1","4",1200);
//        redisTemplate.set("replace:2","5",1200);
//        redisTemplate.set("replace:3","6",1200);

        //扫描出来 pinnied:后面是被替换的id  而value是置顶的
        List<String> replaceList = redisTemplate.scan("replace:");

        for (String key:replaceList){
            String replaceId = key.substring(key.indexOf(":") + 1);

            String pinniedId = redisTemplate.get(key);

            //判断置顶的是否开始运行了
            MayiPayList pinnied = mayiPayListService.getById(pinniedId);
            if (pinnied.getReachCount() > 0){
                //开始执行了之后，就将被替换的状态修改为等待
                MayiPayList replace = mayiPayListService.getById(replaceId);
                replace.setStatus(MayiPayEnums.PAY_AND_RUNING);
                mayiPayListService.updateById(replace);

                // 从redis中删除这个key
                redisTemplate.del(key);
            }

        }
    }
}
